import socket



def newSocketHandler(new_socket, ip_port):
    recv_data = new_socket.recv(1024).decode()
    if not recv_data:
        print("%s用户已经下线" % str(ip_port))
        new_socket.close()
        return 
    print("欢迎%s" %str(ip_port))
    response_line = "HTTP/1.1 200 OK\r\n"
    response_header = "Content-Type: text/html;charset=utf-8\r\n"
    response_blank = "\r\n"
    #  全路径的坑
    with open('/Users/yangjiankun/Documents/python_review/web_serve_easy/static/index.html', 'rb') as file:
        response_body = file.read()
    response = (response_line + response_header + response_blank).encode() +response_body
    new_socket.send(response)
    new_socket.close()


tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                            # 当前套接字   设置 地址重用
tcp_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
tcp_socket.bind(("", 8080))
# 设置监听， 让套接字由主动变成被动接收
tcp_socket.listen(128)
while True:
    new_socket, ip_port = tcp_socket.accept()
    newSocketHandler(new_socket, ip_port)

